//
//  YYScanVC.m
//  Project
//
//  Created by Yown on 2024/1/25.
//

#import "YYScanVC.h"
#import "YYScanView.h"

#import <BIBluetoothModule/BIBluetoothManager.h>
#import <Masonry/Masonry.h>

#import <BIToolModule/NSObject+HUD.h>
#import <BIProjectModule/BIAppDefine.h>

@interface YYScanVC ()

@property (nonatomic) YYScanView *scanView;

@end

@implementation YYScanVC

+ (void)load {
    [[BIRouteManager sharedInstance] registerCMD:@"bluetoothScan" objectOrClass:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshBluetoothList:) name:kAllBluetoothListNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshBluetoothState:) name:kBluetoothConnectResultNotification object:nil];
    
    [self setupViews];
    [self setupLayouts];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[BIBluetoothManager sharedInstance] scanBluetoothList];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[BIBluetoothManager sharedInstance] stopScan];
}

- (void)setupViews {
    self.yy_navigationItem.title = BILocalizedString(@"scan_title");
    self.yy_navigationBar.naviBgColor = [UIColor loadColorFromString:@"#F6F6F6"];
    
    self.scanView = [YYScanView view];
    @weakify(self);
    self.scanView.connectBlock = ^{
        @strongify(self);
        [self showActivityHUD];
    };
    [self.view addSubview:self.scanView];
}

- (void)setupLayouts {
    [self.scanView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(BINavigationBarHeight);
    }];
}

#pragma mark - Notification

- (void)refreshBluetoothList:(NSNotification *)notification {
    [self.scanView reloadData];
}

- (void)refreshBluetoothState:(NSNotification *)notification {
    [self hideActivityHUD];
    // 如果连接成功，则返回到首页
    BIBluetoothModel *model = notification.object;
    if (model.state == kBIBluetoothConnected) {
        @weakify(self);
        [self showTextHUDWithTitle:BILocalizedString(@"hud_succeed") afterDelay:1.0 completionBlock:^{
            @strongify(self);
            [self.navigationController popViewControllerAnimated:YES];
        }];
    } else if (model.state == kBIBluetoothDisconnected) {
        [self showTextHUDWithTitle:BILocalizedString(@"hud_failure") afterDelay:2.0 completionBlock:nil];
    }
}

@end
